package com.github.catvod.spider;

import android.text.TextUtils;

import com.github.catvod.bean.Class;
import com.github.catvod.bean.Result;
import com.github.catvod.bean.Vod;
import com.github.catvod.crawler.Spider;
import com.github.catvod.net.OkHttp;
import com.github.catvod.net.OkResult;
import com.github.catvod.utils.Json;
import com.github.catvod.utils.Util;

import org.json.JSONArray;
import org.json.JSONObject;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * @author fs
 * 2025/2/5
 * 4k影视:https://www.4kvm.tv/
 */
public class FourKTV extends Spider {

    private static final String siteUrl = "https://www.4kvm.tv/";
    private static final String searchUrl = siteUrl+"xssearch";
    private Map<String, String> getHeaders() {
        Map<String, String> header = new HashMap<>();
        header.put("User-Agent", Util.CHROME);
        return header;
    }

    @Override
    public String homeContent(boolean filter) throws Exception {
        List<com.github.catvod.bean.Class> classes = new ArrayList<>();
        String[] typeIdList = {"movies", "tvshows", "classify/meiju", "classify/guochan","classify/hanju","classify/fanju"};
        String[] typeNameList = {"电影", "电视剧", "美剧", "国产剧", "韩剧", "番剧"};
        for (int i = 0; i < typeNameList.length; i++) {
            classes.add(new Class(typeIdList[i], typeNameList[i]));
        }
        return Result.string(classes, new ArrayList<>());
    }


    @Override
    public String categoryContent(String tid, String pg, boolean filter, HashMap<String, String> extend) throws Exception {
        System.out.println(siteUrl + tid+"/page/"+pg);
        Document doc = Jsoup.parse(OkHttp.string(siteUrl + tid+"/page/"+pg, getHeaders()));
        List<Vod> list = parseCatagoryHtmlVod(doc);
        return Result.string(Integer.parseInt(pg),Integer.parseInt(pg)+1,20,list.size(),list);
    }


    @Override
    public String detailContent(List<String> ids) throws Exception {
        String id = ids.get(0);
        // 进行判断是电视剧
        if (id.contains("tvshows")){
            // 电视剧
            String html = OkHttp.string(id, getHeaders());
            Document doc = Jsoup.parse(html);
            String pic = doc.select(".poster > img").attr("src");
            String name = doc.select(".poster > img").attr("alt");
            String desc = doc.select(".description > p").text();
            Elements fromItemList = doc.select("#seasons > div.se-c");
            ArrayList<String> fromLinks = new ArrayList<>();
            ArrayList<String> fromNames = new ArrayList<>();
            ArrayList<String> playUrls = new ArrayList<>();
            Vod vod = new Vod();
            for (Element from : fromItemList) {
                // 进行判断是否包含se-a
                if (from.select("div.se-a").isEmpty()){
                    String fromName = "第"+from.select("span.se-t").text().concat("季");
                    String fromLink = from.select("a").attr("href");
                    fromLinks.add(fromLink);
                    fromNames.add(fromName);
                }else {
                    // 剧集可直接进行播放
                    desc=doc.select("div.wp-content > p").text();
                    fromNames.add("第一季");
                    Elements items = from.select("div.se-a > ul.episodios > li");
                    for (Element item : items) {
                        String playUrl = item.select("div.episodiotitle > a").attr("href");
                        String playName = item.select("div.episodiotitle > a").text();
                        playUrls.add(playName+"$"+playUrl+"#");
                    }
                }

            }
            // 进行请求获取每个播放的链接
            for (String fromLink : fromLinks) {
                String htmlFrom = OkHttp.string(fromLink, getHeaders());
                String resutl = Util.findByRegex("ifsrc:'(.*)',", htmlFrom, 1);
                String lins = Util.findByRegex(" videourls:\\[(.*)\\],", htmlFrom, 1);
                JSONArray lin_arr = new JSONArray(lins);
                StringBuilder stringBuilder = new StringBuilder();
                for (int i = 0; i < lin_arr.length(); i++) {
                    // 如果是最后一集最后不加#
                    if (i == lin_arr.length()-1){
                        stringBuilder.append("第").append(i+1).append("集$").append(resutl).append("&source=0&ep=").append(i);
                    }else{
                        stringBuilder.append("第").append(i+1).append("集$").append(resutl).append("&source=0&ep=").append(i).append("#");
                    }
                }
                playUrls.add(stringBuilder.toString());
            }
            vod.setVodId(id);
            vod.setVodPic(pic);
            vod.setVodName(name);
            vod.setVodPic(pic);
            // 进行判断设置的是否是番剧
            if (playUrls.get(0).contains("episodes")){
                String joined = TextUtils.join("", playUrls);
                // 进行删除最后的#
                vod.setVodPlayUrl(joined.substring(0, joined.length() - 1));
            }else{
                vod.setVodPlayUrl(TextUtils.join("$$$", playUrls));
            }
            vod.setVodPlayFrom(TextUtils.join("$$$", fromNames));
            vod.setVodContent(desc);
            return Result.string(vod);
        }
        // 电影
        String html = OkHttp.string(id, getHeaders());
        Document doc = Jsoup.parse(html);
        String pic = doc.select(".poster > img").attr("src");
        String name = doc.select(".poster > img").attr("alt");
        String desc = doc.select(".description > p").text();
        String vodId = Jsoup.parse(html).select("#dooplay-ajax-counter").attr("data-postid");
        String result = Util.findByRegex("var dtAjax =(.*);", html, 1);
        JSONObject dtAjax = Json.parseJson(result);
        String url_api = dtAjax.getString("url_api");
        HashMap<String, String> params = new HashMap<>();
        params.put("type", "movie");
        params.put("source", "1");
        String api_result = OkHttp.string(url_api + vodId, params, getHeaders());
        JSONObject api_json = Json.parseJson(api_result);
        String playInfoUrl = api_json.getString("embed_url");
        String playHtml = OkHttp.string(playInfoUrl, getHeaders());
        String m3u8 = Util.findByRegex("https?://[^\"']*\\.m3u8", playHtml, 0);
        Vod vod = new Vod();
        vod.setVodId(id);
        vod.setVodName(name);
        vod.setVodPic(pic);
        vod.setVodPlayFrom("4K");
        vod.setVodPlayUrl("4k$"+m3u8);
        vod.setVodContent(desc);
        return Result.string(vod);
    }

    @Override
    public String playerContent(String flag, String id, List<String> vipFlags) throws Exception {
        String playUrl=id;
        if (playUrl.contains("episodes")){
            // 特殊番剧类型
            String html = OkHttp.string(playUrl, getHeaders());
            String result = Util.findByRegex("var dtAjax =(.*);", html, 1);
            String vodId = Jsoup.parse(html).select("#dooplay-ajax-counter").attr("data-postid");
            JSONObject dtAjax = Json.parseJson(result);
            String url_api = dtAjax.getString("url_api");
            HashMap<String, String> params = new HashMap<>();
            params.put("type", "tv");
            params.put("source", "1");
            String api_result = OkHttp.string(url_api + vodId, params, getHeaders());
            JSONObject api_json = Json.parseJson(api_result);
            String playInfoUrl = api_json.getString("embed_url");
            String playHtml = OkHttp.string(playInfoUrl, getHeaders());
            String m3u8 = Util.findByRegex("https?://[^\"']*\\.m3u8", playHtml, 0);
            playUrl=m3u8;
        }
        // 进行判断播放的是电影还是电视剧
        if (playUrl.contains("artplayer")){
            System.out.println("播放的是电视剧");
            // 电视剧
            String html = OkHttp.string(playUrl, getHeaders());
            String m3u8 = Util.findByRegex("https?://[^\"']*\\.m3u8", html, 0);
            //发起请求获取响应类型
            // 创建 OkHttpClient，禁止自动重定向
            OkHttpClient client = new OkHttpClient.Builder()
                    .followRedirects(false) // 禁止自动重定向
                    .build();
            Request.Builder builder = new Request.Builder();
            // 进行添加请求头
            for (String key : getHeaders().keySet()) {
                builder.addHeader(key, Objects.requireNonNull(getHeaders().get(key)));
            }
            // 构建请求
            Request request = builder.url(m3u8)
                    .build();
            try {
                // 发起请求
                Response response = client.newCall(request).execute();
                // 获取响应类型
                String contentType = response.header("Content-Type");
                if (contentType != null && contentType.contains("video/mp4")){
                    // 进行获取location
                    String location = response.header("Location");
                    return Result.get().url(location).header(getHeaders()).string();
                }
                // 关闭响应
                response.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // 进行判断返回m3u8
            return Result.get().url(m3u8).header(getHeaders()).string();
        }
        return Result.get().url(playUrl).header(getHeaders()).string();
    }

    @Override
    public String searchContent(String key, boolean quick) throws Exception {
        HashMap<String, String> params = new HashMap<>();
        params.put("s", key);
        Document doc = Jsoup.parse(OkHttp.string(searchUrl, params, getHeaders()));
        List<Vod> list = seachVod(doc);
        return Result.string(list);
    }

    private List<Vod> seachVod(Document doc) {
        Elements itemList = doc.select("div.search-page > div.result-item");
        List<Vod> list = new ArrayList<>();
        for (Element item : itemList) {
            String pic = item.select("div.image > div.thumbnail > a > img").attr("src");
            String remarks = item.select("div.image > div.thumbnail > a > span").text();
            String id = item.select("div.details > .title > a").attr("href");
            String name = item.select("div.details > .title > a").text();
            list.add(new Vod(id, name, pic, remarks));
        }
        return list;
    }

    private List<Vod> parseCatagoryHtmlVod(Document doc) {
        // 定义选择器
        String[] selectors = {
                "#archive-content > article",
                "div.items > article.item"
        };
        List<Vod> list = new ArrayList<>();
        for (String selector : selectors) {
            Elements itemList = doc.select(selector);
            if (!itemList.isEmpty()) {
                list.addAll(parseItems(itemList));
                break; // 找到匹配的选择器后退出循环
            }
        }
        return list;
    }
    private List<Vod> parseItems(Elements itemList) {
        List<Vod> list = new ArrayList<>();
        for (Element item : itemList) {
            String pic = item.select("div.poster > img").attr("src");
            String id = item.select("div.data > h3 > a").attr("href");
            String title = item.select("div.data > h3 > a").text();
            String remark = item.select("div.poster > div.rating").text();
            list.add(new Vod(id, title, pic, remark));
        }
        return list;
    }
}
